
package com.uziot.bucket.common.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述: <br>
 * 获取堆栈错误信息
 *
 * @author shidt
 * @date 2020-05-11 23:04
 */
public class ThrowableUtil {

    /**
     * 获取堆栈信息
     */
    public static String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        try (PrintWriter pw = new PrintWriter(sw)) {
            throwable.printStackTrace(pw);
            return sw.toString();
        }
    }

    public static Throwable[] getThrowables(Throwable throwable) {
        List<Throwable> list = getThrowableList(throwable);
        return list.toArray(new Throwable[0]);
    }

    public static List<Throwable> getThrowableList(Throwable throwable) {
        ArrayList<Throwable> list;
        for (list = new ArrayList<>();
             throwable != null && !list.contains(throwable);
             throwable = throwable.getCause()) {
            list.add(throwable);
        }
        return list;
    }

}
